package fsahoraires.gui.pages;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;

import fsahoraires.cours.Cours;

public class CoursPage extends EditPage {

	private Cours cours;
	private Text titre, abreviation, credits, heures;
	private boolean dontSet = false, dontUpdate = false;

	public CoursPage(Cours cours) {
		super("Cours", "cours.png");
		this.cours = cours;
	}

	protected void initFields() {
		addLabelField("Code", cours.getCode());

		titre = addTextField("Intitulé");
		titre.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!dontSet) {
					dontUpdate = true;
					cours.setTitre(titre.getText());
					dontUpdate = false;
				}
			}
		});

		abreviation = addTextField("Abréviation");
		abreviation.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!dontSet) {
					dontUpdate = true;
					cours.setAbreviation(abreviation.getText());
					dontUpdate = false;
				}
			}
		});

		credits = addTextField("Crédits");
		credits.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!dontSet) {
					try {
						dontUpdate = true;
						cours.setCredits(Float.parseFloat(credits.getText()));
						dontUpdate = false;
					} catch (NumberFormatException ex) {
					}
				}
			}
		});

		heures = addTextField("Heures");
		heures.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (!dontSet) {
					try {
						dontUpdate = true;
						cours.setHeures(Float.parseFloat(heures.getText()));
						dontUpdate = false;
					} catch (NumberFormatException ex) {
					}
				}
			}
		});

		Composite update = addCompositeField("Récupération");
		update.setLayout(new RowLayout(SWT.HORIZONTAL));
		final Combo fetchType = new Combo(update, SWT.DROP_DOWN | SWT.READ_ONLY);
		fetchType.add("Description + Horaire");
		fetchType.add("Description");
		fetchType.add("Horaire");
		fetchType.select(0);
		fetchType.pack();
		final Button fetch = new Button(update, SWT.PUSH);
		fetch.setText("Mise à jour");
		fetch.pack();
		fetch.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				boolean desc = false, horaire = false;
				switch (fetchType.getSelectionIndex()) {
				case 0:
					desc = true;
					horaire = true;
					break;
				case 1:
					desc = true;
					break;
				case 2:
					horaire = true;
					break;
				}
				if (desc) {
					cours.setTitre("");
					cours.setCredits(0);
					cours.setHeures(0);
				}
				cours.fetch(desc, horaire);
			}
		});
	}

	public void update() {
		if (dontUpdate)
			return;
		dontSet = true;
		titre.setText(cours.getTitre());
		abreviation.setText(cours.getAbreviation());
		credits.setText(cours.getCredits() + "");
		heures.setText(cours.getHeures() + "");
		dontSet = false;
	}

}
